﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Mrsoft.Common
{
    /// <summary>
    /// 对Config的进一步封装
    /// 实现了Config的自动存取 控件绑定和控件集中管理注册功能
    /// 同时附加对内容文本进行base64编码保证文本的完整和XML文件的正确
    /// </summary>
    public class Base64Config
    {
        public Base64Config(string fileName, string treePath, string value)
        {
            this._value = new Config<string>(fileName, treePath, Convert.ToBase64String(Encoding.UTF8.GetBytes(value)));
        }

        private readonly Config<string> _value;
        public string Value
        {
            set
            {
                var temp = Convert.ToBase64String(Encoding.UTF8.GetBytes(value));
                if (!this._value.Value.Equals(value))
                {
                    this._value.Value = temp;
                }
            }

            get
            {
                return Encoding.UTF8.GetString(Convert.FromBase64String(_value.Value));
            }
        }

        /// <summary>
        /// 设置控件绑定
        /// </summary>
        /// <param name="control"></param>
        /// <param name="propertyName"></param>
        public void SetBind(Control control, string propertyName)
        {
            ConfigFactory.BindingControlRegister(control);
            control.DataBindings.Clear();
            control.DataBindings.Add(propertyName, this, "Value", true, DataSourceUpdateMode.OnPropertyChanged);
        }

        public override string ToString()
        {
            return Value;
        }
    }
}
